
package com.hanhai.zrb.api.biz.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hanhai.common.cache.Cache;
import com.hanhai.common.result.ValidateCodeSendResult;
import com.hanhai.common.result.ValidateCodeSendResult.ResultCodeEnum;
import com.hanhai.common.util.DateUtil;
import com.hanhai.common.util.MD5Util;
import com.hanhai.zrb.api.biz.result.UserCenterResult;
import com.hanhai.zrb.api.biz.service.MessageSendService;
import com.hanhai.zrb.api.biz.service.UserRegisterCheckService;
import com.hanhai.zrb.api.biz.service.UserRegisterService;
import com.hanhai.zrb.api.biz.service.UserSequenceService;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.api.biz.service.ValidateCodeSendService;
import com.hanhai.zrb.model.common.ValidateCodeSend;
import com.hanhai.zrb.model.common.ValidateCodeSend.BizTypeEnum;
import com.hanhai.zrb.model.common.ValidateCodeSend.SendTypeEnum;
import com.hanhai.zrb.model.common.vo.CodeSendTimesForCache;
import com.hanhai.zrb.model.user.User;
import com.hanhai.zrb.model.user.vo.UserRegisterVo;

@Service("userRegisterService")
public class UserRegisterServiceImpl implements UserRegisterService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	private UserService userService;
	
	@Resource
	private UserSequenceService userSequenceService;

	@Resource
	private Cache defaultCache;

	@Resource
	private ValidateCodeSendService validateCodeSendService;
	@Resource
	private UserRegisterCheckService userRegisterCheckService;

	
	@Resource
	private MessageSendService messageSendService;
	
	@Override
	@Transactional
	public void saveUser(User user) {
		userService.saveUser(user);
	}

	/**
	 * 发送手机验证码
	 */
	@Override
	public UserCenterResult sendSMSCode(String mobileNum, String key,
			BizTypeEnum type, int codeType) {
		UserCenterResult result = new UserCenterResult(true,
				new ArrayList<String>());
		UserCenterResult checkResult = userRegisterCheckService
				.checkMobileOrEmailExist(mobileNum, StringUtils.EMPTY, codeType);
		if (!checkResult.isSuccess()) {
			result.setSuccess(false);
			result.setMsg(checkResult.getMsg());
			return result;
		}
		Date now  = new Date();
		key += mobileNum;
		CodeSendTimesForCache codeSendTimes = (CodeSendTimesForCache) defaultCache.getValue(key);
		//为空或者不是当天新建对象
		if(codeSendTimes==null||!DateUtil.isSameDay(codeSendTimes.getLastSendTime(),now)){
			codeSendTimes = new CodeSendTimesForCache();
			codeSendTimes.setIdentifyingCode(mobileNum);
			codeSendTimes.setSendTimes(0);
			codeSendTimes.setLastSendTime(now);
			codeSendTimes.setCreateTime(now);
			
		}else {
			//次数上线为到就++，到了就返回错误码
			if(CodeSendTimesForCache.MAXSENDTIMESONEDAY >codeSendTimes.getSendTimes()){
				codeSendTimes.setSendTimes(codeSendTimes.getSendTimes() + 1);
				codeSendTimes.setLastSendTime(Calendar.getInstance().getTime());
			}else{
				result.setSuccess(false);
				result.setMsg("每天只能发送"+CodeSendTimesForCache.MAXSENDTIMESONEDAY+"次");
				return result;
			}			
		}
				
		ValidateCodeSend validateCodeSend = new ValidateCodeSend();
		validateCodeSend.setSendIdentity(mobileNum);
		validateCodeSend.setSendType(SendTypeEnum.SMS);
		validateCodeSend.setBizType(type);
		validateCodeSend.setEffectMinute(15);
		validateCodeSendService
				.createAndSendCheckCode(validateCodeSend);
		//验证码发送成功，更新发送次数到缓存
		defaultCache.add(key, codeSendTimes, DateUtil.getSecondsBetweenTwoDate(DateUtil.getTheDayEndTime(now.getTime()),now.getTime()));

		return result;
	}

	
	/**
	 * 邮箱发送验证码
	 */
	@Override
	public UserCenterResult sendCodeByEmail(String email, String key,
			BizTypeEnum type, int codeType) {
		UserCenterResult result = new UserCenterResult(true,
				new ArrayList<String>());
		UserCenterResult checkResult = userRegisterCheckService
				.checkMobileOrEmailExist(StringUtils.EMPTY, email, codeType);
		if (!checkResult.isSuccess()) {
			result.setSuccess(false);
			result.setMsg(checkResult.getMsg());
			return result;
		}

		key += email;
		
		CodeSendTimesForCache codeSendTimes = (CodeSendTimesForCache) defaultCache
				.getValue(key);
		Date now = new Date();
		// 为空或者不是当天新建对象
		if (codeSendTimes == null
				|| !DateUtil.isSameDay(codeSendTimes.getLastSendTime(), now)) {
			codeSendTimes = new CodeSendTimesForCache();
			codeSendTimes.setIdentifyingCode(email);
			codeSendTimes.setSendTimes(0);
			codeSendTimes.setLastSendTime(now);
			codeSendTimes.setCreateTime(now);

		} else {
			// 次数上线为到就++，到了就返回错误码
			if (CodeSendTimesForCache.MAXSENDTIMESONEDAY > codeSendTimes
					.getSendTimes()) {
				codeSendTimes.setSendTimes(codeSendTimes.getSendTimes() + 1);
				codeSendTimes.setLastSendTime(Calendar.getInstance().getTime());
			} else {
				result.setSuccess(false);
				result.setMsg("每天只能发送"
						+ CodeSendTimesForCache.MAXSENDTIMESONEDAY + "次");
				return result;
			}

		}

		ValidateCodeSend validateCodeSend = new ValidateCodeSend();
		validateCodeSend.setSendIdentity(email);
		validateCodeSend.setSendType(SendTypeEnum.EMAIL);
		validateCodeSend.setBizType(type);
		validateCodeSend.setEffectMinute(2);
		validateCodeSendService.createAndSendCheckCode(validateCodeSend);
		// 验证码发送成功，更新发送次数到缓存
		defaultCache.add(key, codeSendTimes, DateUtil.getSecondsBetweenTwoDate(
				DateUtil.getTheDayEndTime(now.getTime()), now.getTime()));
		return result;

	}

	/**
	 * 校验发送邮件
	 */
	private UserCenterResult checkSendEmail(String emailAddress, int type) {
		UserCenterResult result = new UserCenterResult(true,
				new ArrayList<String>());
		// 判断数据库该邮箱是否已经存在
		UserCenterResult checkResult = userRegisterCheckService
				.checkMobileOrEmailExist(StringUtils.EMPTY, emailAddress, type);
		if (!checkResult.isSuccess()) {
			result.setSuccess(false);
			result.setMsg(checkResult.getMsg());
			return result;
		}
		String key = "sendIdentifyingEmail_" + emailAddress;
		CodeSendTimesForCache codeSendTimes = (CodeSendTimesForCache) defaultCache
				.getValue(key);
		Date now = new Date();
		// 为空或者不是当天新建对象
		if (codeSendTimes == null
				|| !DateUtil.isSameDay(codeSendTimes.getLastSendTime(), now)) {
			codeSendTimes = new CodeSendTimesForCache();
			codeSendTimes.setIdentifyingCode(emailAddress);
			codeSendTimes.setSendTimes(0);
			codeSendTimes.setLastSendTime(now);
			codeSendTimes.setCreateTime(now);

		} else {
			// 次数上线为到就++，到了就返回错误码
			if (CodeSendTimesForCache.MAXSENDTIMESONEDAY > codeSendTimes
					.getSendTimes()) {
				codeSendTimes.setSendTimes(codeSendTimes.getSendTimes() + 1);
				codeSendTimes.setLastSendTime(Calendar.getInstance().getTime());
			} else {
				result.setSuccess(false);
				result.setMsg("每天只能发送"
						+ CodeSendTimesForCache.MAXSENDTIMESONEDAY + "次");
				return result;
			}

		}
		// 验证码发送成功，更新发送次数到缓存
		defaultCache.add(key, codeSendTimes, DateUtil.getSecondsBetweenTwoDate(
				DateUtil.getTheDayEndTime(now.getTime()), now.getTime()));
		return result;
	}

	

	@Override
	@Transactional
	public UserCenterResult doRegisterByMobile(UserRegisterVo userRegisterVo) {
		UserCenterResult result = new UserCenterResult();
		String password = userRegisterVo.getPassword();

		User user = new User();
		String umobile = userRegisterVo.getUmobile();
	
		
		user.setUmobile(umobile);
		
		String uname = userRegisterVo.getUname();
		user.setPassword(MD5Util.sha1(password));
		user.setUname(uname);
		
		user.setUid(userSequenceService.getNextUserId());
		/*if(userRegisterVo.getUserType()==1){
			user.setUid(userSequenceService.getNextUserId());
			user.setOrg(userRegisterVo.getOrg());
			
		}else{
			user.setUid(userSequenceService.getNextGovmentUserId());
		}*/
		
		boolean bool = userService.saveUser(user);
		if(bool){
			result.setSuccess(true);	
			
//	           try {
//	        	   if(null!=user.getUmobile()){
//	        	   user = userService.findByPhone(user.getUmobile());
//	   			   if(null!=user){
//	   					List<Long> receiverUids = new ArrayList<Long>();
//	   					receiverUids.add(user.getUid());
//	   					String content = null;
//	   					MessageBizType bizType = MessageBizType.user_regiester_succes;
//	   					if(userRegisterVo.getUserType()==1&&StringUtils.isEmpty(userRegisterVo.getOrg())){
//	   						bizType=MessageBizType.investor_regiester_succes_without_org;
//	   					}
//	   					messageSendService.createNotifyMessage(receiverUids, content, bizType, "");	
//	   			   }
//	        	   }
//	   		} catch (Exception e) {
//	   		}
			
		}else{
			result.setMsg("重复注册");
		}
		
		return result;
	}


	@Override
	public UserCenterResult checkSMSCode(String mobilephone, String code,
			BizTypeEnum bizType) {
		UserCenterResult userCenterResult = new UserCenterResult();
		ValidateCodeSend validateCodeSend = new ValidateCodeSend();
		validateCodeSend.setSendIdentity(mobilephone);
		// validateCodeSend.setSendType(SendTypeEnum.SMS);
		validateCodeSend.setBizType(bizType);
		ValidateCodeSendResult valResult = validateCodeSendService.check(
				validateCodeSend, code);
		if (!valResult.isSuccess()) {
			userCenterResult.setSuccess(false);
			
			ResultCodeEnum codeEnum = ValidateCodeSendResult.ResultCodeEnum.getValueByName(valResult.getResultCode());
			if(codeEnum!=null){
				userCenterResult.setMsg(codeEnum.getDesc());
			}else{
				userCenterResult.setMsg(valResult.getResultCode());
			}
			
		} else {
			userCenterResult.setSuccess(true);
		}
		return userCenterResult;
	}

	/*
	@Override
	public UserCenterResult registerHuanxinImByUid(Long uid){
		User user = this.userService.findById(uid);
		if(user == null){
			throw new RuntimeException();
		}
		return this.registerHuanxinIm(user);		
	}
	
	@Override
	public UserCenterResult getHuanxinImInfo(Long uid){
		UserCenterResult result = new UserCenterResult();
		User user = this.userService.findById(uid);
		if(user == null){
			throw new RuntimeException();
		}
		UserIm userIm = userImService.getByUidAndType(uid, UserIm.type.huanxin);
		if(userIm == null){			
			result = this.registerHuanxinIm(user);
			if(result.isSuccess()){
				userIm = result.getUserIm();
			}
		}
		Map<String,Object> huanxinInfoMap =  this.getExistedHuanxinInfo(userIm,user);
		result.setSuccess(true);
		result.setHuanxinInfoMap(huanxinInfoMap);
		return result;
	}
	private UserCenterResult registerHuanxinIm(User user){
		UserCenterResult result = new UserCenterResult();
		
		Map<String,Object> huanxinInfoMap = this.getInitHuanxinImInfo(user);
		String username = huanxinInfoMap.get("huanxinImUsername").toString();
		String password = huanxinInfoMap.get("huanxinImPassword").toString();
		String nickname = huanxinInfoMap.get("huanxinImNickname").toString();
		
		HuanxinUserApiResult huanxinResult = this.remoteHuanxinUserApiFacade.registerImUser(username, password, nickname);
		if(huanxinResult.isSuccess()){
			result.setSuccess(true);
			result.setHuanxinInfoMap(huanxinInfoMap);
			UserIm userIm = new UserIm();
			userIm.setUid(user.getUid());
			userIm.setUname(username);
			userIm.setPawd(password);
			userIm.setType("huanxin");
			userImService.create(userIm);
			result.setUserIm(userIm);
		}
		
		return result;
	}

	private Map<String,Object> getExistedHuanxinInfo(UserIm userIm,User user){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("huanxinImUsername", userIm.getUname());
		map.put("huanxinImPassword", userIm.getPawd());
		map.put("huanxinImNickname", user.getUname());
		return map;
	}
	
	private Map<String,Object> getInitHuanxinImInfo(User user){
		String env = SystemConstants.env;
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("huanxinImUsername", env+"_"+user.getUid());
		map.put("huanxinImPassword", MD5Util.md5(user.getUid().toString()));
		map.put("huanxinImNickname", user.getUname());
		return map;
	}*/
}
